<template>
  <div id="canvas-container">
    
  </div>
</template>

<script setup lang="ts">
import { ref ,reactive,defineProps,defineEmits} from 'vue';
// import PDFJS from '@/assets/pdfjs-dist/build/pdf.js'
import * as PdfJs from 'pdfjs-dist/legacy/build/pdf.js' 
import type { RenderParameters } from 'pdfjs-dist/types/src/display/api';

import { TextLayerBuilder } from 'pdfjs-dist/web/pdf_viewer';
import 'pdfjs-dist/web/pdf_viewer.css';
PdfJs.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.9.179/pdf.worker.min.js';
interface EmitsModel{
    (e:'getPageTotal',pageTotal:number):void,

}
  const props = defineProps<{
    page:number
  }>()
  const url = ref('/src/assets/pdf/阿里前端开发规范.pdf')
  const scale = ref(1.5) 
  const emits = defineEmits<EmitsModel>()
  // 渲染多页pdf
  PdfJs.getDocument(url.value).promise.then((pdf) => {
    emits('getPageTotal',pdf.numPages)
    for (let i = 1; i < pdf.numPages; i++) {
      renderPdf(i,pdf)
    }
    // return pdf.getPage(props.page);
  })
  const renderPdf = (num:number,pdf:any)=>{
    pdf.getPage(num).then(async (page:any)=>{
      // 获取根元素
      const canvasContainer = document.getElementById('canvas-container')
      // var scale:number = 1.5;
      // 获取pdf尺寸
      var viewport = page.getViewport({scale:scale.value});
      let pageDiv = document.createElement('div')
      pageDiv.setAttribute('id', 'page-' + (page.pageIndex + 1));
      pageDiv.setAttribute('style', 'position: relative');
      canvasContainer?.appendChild(pageDiv)
      let canvas = document.createElement('canvas');
      pageDiv.appendChild(canvas);
      let context:CanvasRenderingContext2D = (canvas as HTMLCanvasElement)!.getContext('2d') as unknown as CanvasRenderingContext2D;
      (canvas as HTMLCanvasElement).height = viewport.height;
      (canvas as HTMLCanvasElement).width = viewport.width;

      // 获取需要渲染的元素
      // var canvas = document.getElementById('pdf-canvas');
      // (canvas as HTMLCanvasElement).height = viewport.height;
      // (canvas as HTMLCanvasElement).width = viewport.width;

      var renderContext:RenderParameters = {
          canvasContext: context,
          viewport: viewport
      };
      // 以上为渲染多页pdf  以下为开始渲染复制文本图层
      page.render(renderContext)
    })

  }

  
</script>

<style lang="scss" scoped>

</style>